package com.mriassl.stream.service.impl;

import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.MessageFormat;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mriassl.stream.constant.TransactionType;
import com.mriassl.stream.domain.BetDO;
import com.mriassl.stream.domain.TransactionDO;
import com.mriassl.stream.lib.rabbitmq.RabbitMQConst;
import com.mriassl.stream.mapper.BetMapper;
import com.mriassl.stream.mapper.TransactionMapper;
import com.mriassl.stream.service.LotteryService;

@Service
public class LotteryServiceImpl implements LotteryService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private BetMapper betMapper;
    @Autowired
    private TransactionMapper transactionMapper;

    @Override
    @Transactional
    public void saveBettingOrder(String betno) {
        BetDO bet = new BetDO();
        bet.setBetno(betno);
        Long userid = 1001L;
        bet.setUserid(userid);
        int price = 100;
        bet.setPrice(price);
        bet.setExpect(new BigDecimal(28876.78));
        bet.setBonus(new BigDecimal(28876.78));
        bet.setIshit((byte) 1);
        bet.setPassway("8x247");
        bet.setOptimizedway((byte)0);
        bet.setReqmultiple((byte)99);
        bet.setPaystate((byte)0);
        bet.setState((byte)1);
        Timestamp time = new Timestamp(System.currentTimeMillis());
        bet.setGmtcreate(time);
        bet.setGmtmodified(time);
        betMapper.insert(bet);
        // 保存事务记录
        TransactionDO transaction = new TransactionDO();
        // 保证每种类型事务编码的唯一
        String orderno = TransactionType.BETTING.getPrefix()+betno;
        transaction.setOrderno(orderno);
        transaction.setExchange(RabbitMQConst.EXCHANGE_FOR_BETTING);
        transaction.setRoutekey(RabbitMQConst.ROUTE_FOR_BETTING);
        String sendinfo = MessageFormat.format("busno:{0},uid:{1},price:{2}", orderno, userid.toString(), price+"");
        transaction.setSendinfo(sendinfo);
        transaction.setGmtcreate(time);
        transaction.setGmtmodified(time);
        transactionMapper.insert(transaction);
        
//        double random = Math.random();
//        System.out.println("=========================random:"+random);
//        if(random > 0.5) {
//            throw new RuntimeException("模拟保存投注信息失败！！");
//        }
        // 发送投注消息
        rabbitTemplate.convertAndSend(RabbitMQConst.EXCHANGE_FOR_BETTING, RabbitMQConst.ROUTE_FOR_BETTING, sendinfo);
    }

    @Override
    @Transactional
    public void updateBettingInvalidByBetno(String betno) {
        betMapper.updateBettingInvalidByBetno(betno);
        transactionMapper.deleteTransactionByOrderno(TransactionType.BETTING.getPrefix()+betno);
    }
    
}
